package com.jshx.sz.gdjt.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import com.jshx.sz.gdjt.R;
import com.jshx.sz.gdjt.bean.TaskListBean;
import com.jshx.sz.gdjt.constant.ApplicationGlobal;
import com.jshx.sz.gdjt.control.HeaderView;
import com.jshx.sz.gdjt.db.DataBaseUtil;
import com.jshx.sz.gdjt.thread.GetTaskThread;
import com.jshx.sz.gdjt.thread.RebackTaskThread;
import com.jshx.sz.gdjt.util.ProgressDialogUtil;
import com.jshx.sz.gdjt.util.ToastUtil;

/**
 * 工具列表界面
 * @author caxiang
 * @time 2013-08-21
 */
public class GetTaskListActivity extends SuperActivity 
{
	
	/**
	 * 标题栏组件
	 */
	private HeaderView header;
	
	/**
	 * 列表组件
	 */
	private ListView getTaskList;
	
	/**
	 * 组件实例化工具
	 */
	private LayoutInflater layoutInflater;
	
	/**
	 * 工具数据容器
	 */
	private ArrayList data=new ArrayList();
	
	/**
	 * 领取或者退回按钮返回的数据
	 */
	private HashMap UpdateTaskReturnMap=new HashMap();
	/**
	 * 
	 */
	private String type;
	
	/**
	 * 领取按钮返回用于处理离线的任务列表数据 格式为ArrayList<Hashmap<String,String>>
	 */
	private ArrayList taskList=new ArrayList();
	
	/**
	 * 页面句柄
	 */
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) 
		{
			int what = msg.what;
			super.handleMessage(msg);
			ProgressDialogUtil.dismiss();
			getTaskList.setAdapter(myAdapter);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gettasklist_activity);
		TAG = "GetTaskListActivity";
		layoutInflater = LayoutInflater.from(this);
		type =   getIntent().getStringExtra("type");
		findView();
		initView();
	}

	/**
	 * 实例化页面组件
	 */
	private void findView() {
		header = (HeaderView)findViewById(R.id.gettasklist_header);
		getTaskList = (ListView)findViewById(R.id.gettasklist);
	}

	/**
	 * 初始化页面数据和页面组件
	 */
	private void initView() {
		if(type.equals("task"))
		{
			header.setTitle("任务领取列表");
			header.setRightButtonClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) {
					proClick( v);
				}
			}, R.drawable.titlebtn_select, "领取");
		}
		else
		{
			header.setTitle("任务退回列表");
			header.setRightButtonClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) {
					proClick( v);
				}
			}, R.drawable.titlebtn_select, "退回");
		}
		header.setLeftButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				GetTaskListActivity.this.finish();
			}
		}, R.drawable.backbtn_select, "返回");
		 
		ProgressDialogUtil.show(this, "获得数据中...", true);
		
		
		//加载要领取的 或者要退回的任务，数据分两层，一层为工作令，一层为相对应的设备
		String userId=ApplicationGlobal.userId;
		String params= ",'userId':'"+userId+"','type':'getTaskListAll'";
		if(type.equals("reback"))
		{
			params+= ",'status':'1'";
		}
		GetTaskThread thread=new GetTaskThread(handler, params,data);
		thread.start();
	}
	
	/**
	 * 
	 */
	private void saveData(){
		
	}
	
	/**
	 * 领取或者 退回按钮操作句柄
	 */
	private Handler handlerClick = new Handler(){
		@Override
		public void handleMessage(Message msg) 
		{
			if(msg.what == ApplicationGlobal.data_missed)
			{
				ProgressDialogUtil.dismiss();
				ToastUtil.showShortToast(GetTaskListActivity.this, "处理失败");
			}
			else if(msg.what == ApplicationGlobal.data_obtained)
			{
				if(type.equals("task"))//领取
				{
					//列表数据保存
					for (int i = 0; i < taskList.size(); i++) {
						DataBaseUtil.insertTaskList((HashMap<String, String>)taskList.get(i));
					}
					
					ProgressDialogUtil.dismiss();
					Intent intent = new Intent(GetTaskListActivity.this, ToolsListActivity.class);
					intent.putExtra("orderNos", orderNos);
					startActivity(intent);
					GetTaskListActivity.this.finish();
				}
				else//退回
				{

					///----------------
					//orderNos 全局变量，格式"工单编号1,工单编号2,......."
					//预留用
					//----------------------
					//数据删除
					if(orderNos != null)
					{
						String[] tempArray = orderNos.split(",");
						DataBaseUtil.deleteTask(tempArray);
					}
					
					ProgressDialogUtil.dismiss();
					ToastUtil.showShortToast(GetTaskListActivity.this, "处理成功");
					data.clear();
					//加载要领取的 或者要退回的任务，数据分两层，一层为工作令，一层为相对应的设备
					String userId=ApplicationGlobal.userId;
					String params= ",'userId':'"+userId+"','type':'getTaskListAll','status':'1'";
					GetTaskThread thread = new GetTaskThread(handler, params,data);
					thread.start();
				}
			}
			super.handleMessage(msg);
		}
		
	};
	
	String orderNos="";
	
	//处理领取或者 退回的响应按钮事件
	private void proClick(View v)
	{
		//获得选择中的工单编号列表
		for(int i=0;i<data.size();i++)
		{
			HashMap map=(HashMap)data.get(i);
			ArrayList temp=(ArrayList)map.get("child");
			for(int j=0;j<temp.size();j++)
			{
				HashMap childMap =(HashMap)temp.get(j);
				if(childMap.containsKey("isSelect"))
				{
					boolean isSelect=(Boolean)(childMap.get("isSelect"));
					if(isSelect)
					{
						orderNos+=childMap.get("operationCode")+",";
					}
				}
			}
		}
		if(orderNos!=null&&!orderNos.equals(""))
		{
			orderNos=orderNos.substring(0,orderNos.length()-1);
		}
		
		//调用后台执行领取或者退回操作
		String userId=ApplicationGlobal.userId;
		String params= ",'userId':'"+userId+"','orderNos':'"+orderNos+"'";
		if(type.equals("task"))//领取
		{
			params+=",'type':'saveTask'";
		}
		else//退回
		{
			params+=",'type':'deleteTask'";
		}
		RebackTaskThread thread=new RebackTaskThread(handlerClick, params,UpdateTaskReturnMap,type,taskList,orderNos);
		thread.start();
	}
	
	ArrayList childList=new ArrayList();
	
	/**
	 * listVIew数据适配器
	 */
	private BaseAdapter myAdapter = new BaseAdapter()
	{
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			HashMap map=(HashMap)data.get(position);
			convertView = layoutInflater.inflate(R.layout.gettask_list_item, null);
			
			final CheckBox check = (CheckBox)convertView.findViewById(R.id.gettask_listitem_checkbox);
			TextView num = (TextView)convertView.findViewById(R.id.gettask_listitem_num);
			TextView state = (TextView)convertView.findViewById(R.id.gettask_listitem_state);
			num.setText(map.get("operationCode")+"");
			state.setText(map.get("status")+"");
			Object obj = map.get("hasSelect");
			if(obj == null || !((Boolean)obj).booleanValue())
			{
				check.setChecked(false);
			}
			else
			{
				check.setChecked(true);
			}
			check.setOnCheckedChangeListener(new OnCheckedChangeListener() 
			{
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					((HashMap)data.get(position)).put("hasSelect", isChecked);
					ArrayList list = ((ArrayList)(((HashMap)data.get(position)).get("child")));
					if(list != null)
					{
						for (int i = 0; i < list.size(); i++) 
						{
							((HashMap)list.get(i)).put("isSelect", isChecked);	
						}
					}
				}
			});
			convertView.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(GetTaskListActivity.this, PopActivity.class);
					intent.putExtra("isImage", false);
					intent.putExtra("isNeedShowCheckBox", true);
					
					//把工作令相关联的设备信息传入
					HashMap map = (HashMap)data.get(position);
					childList=(ArrayList)map.get("child");
					String operationCode = (String)map.get("order1");
					TaskListBean lb= new TaskListBean();
					lb.setreturnList(childList);
					intent.putExtra("taskList", lb);
					intent.putExtra("position", position);
					intent.putExtra("checkBoxChecked", check.isChecked());
					intent.putExtra("operatonCode", operationCode);
					startActivityForResult(intent, 0);
				}
			});
			 
			return convertView;
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public Object getItem(int position) {
			return data.get(position);
		}
		
		@Override
		public int getCount() {
			return data.size();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(resultCode == RESULT_OK && requestCode == 0)
		{
			if(data != null && data.getParcelableExtra("taskList") != null && data.getIntExtra("position", -1) >= 0)
			{
				TaskListBean lb= data.getParcelableExtra("taskList");
				ArrayList list = lb.getreturnList();
				((HashMap)GetTaskListActivity.this.data.get(data.getIntExtra("position", -1))).put("child", list);
//				list = (ArrayList)((HashMap)GetTaskListActivity.this.data.get(data.getIntExtra("position", -1))).get("child");
//				ToastUtil.showLongToast(GetTaskListActivity.this, "------->" + ((HashMap)list.get(0)).get("isSelect"));
				if(list != null && list.size() > 0)
				{
					int count = 0;
					for (int i = 0; i < list.size(); i++) 
					{
						Object obj = ((HashMap)list.get(i)).get("isSelect");
						if(obj != null && ((Boolean)obj).booleanValue())
						{
							count++;
							break;
						}
					}
					if(count > 0)
					{
						((HashMap)GetTaskListActivity.this.data.get(data.getIntExtra("position", -1))).put("hasSelect", true);
					}
					else
					{
						((HashMap)GetTaskListActivity.this.data.get(data.getIntExtra("position", -1))).put("hasSelect", false);
					}
				}
				myAdapter.notifyDataSetChanged();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}
